import java.net.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.*;

public class NetworktableServer extends Thread{
	private ArrayList<NCTServerThread> allClients;
	private ServerSocket serverSocket;
    static boolean listening = false;
    private int port;
	
	public NetworktableServer(int port){
		serverSocket = null;
        listening = true;
        this.port = port;
        allClients = new ArrayList<NCTServerThread>();
	}
	
	public void stopServer(){
		listening = false;
		// TODO: Disconnect connections
		try {
			serverSocket.close();
		} catch (IOException e) {
			System.out.println("Uhmm... what the...?");
		}
		stop();
	}
	
    public void run() {
        serverSocket = null;
        boolean listening = true;

        try {
            serverSocket = new ServerSocket(port);
            while (listening){
            	NCTServerThread newThread = new NCTServerThread(serverSocket.accept());
            	sendToAll("join "+newThread.getPlayerName());
            	for(NCTServerThread tmp:allClients){
            		System.out.println("sent " +tmp.getPlayerName() );
            		newThread.send("join "+tmp.getPlayerName());
            	}
            	newThread.start();
            	allClients.add(newThread);
            }
            serverSocket.close();
        } catch (IOException e) {
        	if (listening) {
        		System.err.println("Could not listen on port: " + port);
        		System.exit(-1);
        	}
        }
    }
    
    public void sendToAll(String pMsg){
    	//System.out.println(pMsg);
    	Iterator<NCTServerThread> it= allClients.iterator();
    	while(it.hasNext()){
    		it.next().send(pMsg);
    	}
    }
    
    
}
